package org.song.service.common;

import cn.hutool.core.lang.Assert;
import org.song.exception.myException.CommonException;
import org.song.util.AliYunUtil;
import org.song.util.SnowflakeUtil;
import org.springframework.lang.NonNull;
import org.springframework.lang.Nullable;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URL;
import java.util.Objects;

/**
 * 文件上传父接口
 */
public interface BaseFileService {

    /**
     * 公共上传文件接口
     *
     * @param savePath
     * @param file
     * @return
     */
    default String baseUploadImage(@NonNull String savePath, @NonNull MultipartFile file) throws IOException {
        // 雪花算法生成保存文件名防止文件名重复被覆盖
        final String objectName = SnowflakeUtil.getNextId() + file.getOriginalFilename();
        String blogImageSavePath = savePath + objectName;
        AliYunUtil.putObjectToOss(blogImageSavePath, file.getInputStream());
        return blogImageSavePath;
    }

    /**
     * 公共文件获取接口
     * @param objectName
     * @return
     */
    default URL baseGetImage( @NonNull String objectName , @Nullable Long expire )  {
        // 主图保存路径
        final URL instanceFromOss = AliYunUtil.getInstanceFromOss( objectName , expire  );
        Assert.isTrue( Objects.nonNull( instanceFromOss ) , () -> new CommonException( "文件获取失败" ) );
        return instanceFromOss;
    }


}
